package org.example.springsecurity_.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
    //自己写一个template
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String,Object> redisTemplate=new RedisTemplate<String,Object>();
        redisTemplate.setConnectionFactory(factory);
        //-设置序列化方式-
        //序列化器，序列object的
        Jackson2JsonRedisSerializer<Object> serializer=new Jackson2JsonRedisSerializer<>(Object.class);//值的序列化器
        //new一个jackson的解析器
        ObjectMapper objectMapper=new ObjectMapper();
        //所有的get，set方法可用,并且允许所有的属性和方法被序列化‌
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //允许多态类型,反序列化时能识别原始类型
        objectMapper.activateDefaultTyping(objectMapper.getPolymorphicTypeValidator(),ObjectMapper.DefaultTyping.NON_FINAL);
        // 将配置好的解析器注入序列化工具
        serializer.setObjectMapper(objectMapper);

        //普通键(包括set等)的序列化方式(String格式存储)
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //普通值的序列化方式(JSON格式存储)
        redisTemplate.setValueSerializer(serializer);

        //hash的序列化方式(String格式存储)
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        //hash的序列化方式(JSON格式存储)
        redisTemplate.setHashKeySerializer(serializer);

        return redisTemplate;
    }
}
